#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " <file_path>" << std::endl;
        return 1;
    }

    const char *file_path = argv[1];

    // 读取文件内容
    std::ifstream file(file_path, std::ios::binary | std::ios::ate);
    if (!file)
    {
        std::cerr << "Error opening file: " << file_path << std::endl;
        return 1;
    }

    std::streamsize size = file.tellg();
    file.seekg(0, std::ios::beg);

    std::vector<char> buffer(size);
    if (!file.read(buffer.data(), size))
    {
        std::cerr << "Error reading file: " << file_path << std::endl;
        return 1;
    }

    using namespace boost::interprocess;

    // 先尝试删除已有的共享内存对象
    shared_memory_object::remove("FileSharedMemory");

    // 创建共享内存对象
    shared_memory_object shm(create_only, "FileSharedMemory", read_write);

    // 设置共享内存的大小
    shm.truncate(size + 256); // 额外的空间用于存储文件名

    // 映射共享内存到当前进程的地址空间
    mapped_region region(shm, read_write);

    // 获取指向共享内存的指针
    void *addr = region.get_address();

    // 将文件名和文件内容写入共享内存
    std::strcpy(static_cast<char *>(addr), file_path);                          // 写入文件名
    std::memcpy(static_cast<char *>(addr) + 256, buffer.data(), buffer.size()); // 写入文件内容

    std::cout << "File content written to shared memory: " << file_path << std::endl;

    return 0;
}
